package com.sunxueqi.framework.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import com.sunxueqi.common.exception.UserException;
import com.sunxueqi.framework.security.LoginUser;
import com.sunxueqi.project.system.service.IMenuService;
import com.sunxueqi.project.system.service.IUserService;
import com.sunxueqi.project.system.vo.User;

import cn.hutool.core.util.ObjectUtil;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
	@Autowired
	private IUserService userService;

	@Autowired
	private IMenuService menuService;
	
	public UserDetails loadUserByUsername(String username) throws UserException {

		User user = userService.selectUserByUsername(username);
		if(ObjectUtil.isEmpty(user)) {
			throw new UserException("user.not.exist");
		}
		return createLoginUser(user);
	}

	public UserDetails createLoginUser(User user) {
		return new LoginUser(user, menuService.selectPermissionsByUser(user));
	}
}
